package com.example.isoftservice.service.email;

import com.example.isoftservice.mapper.UserMapper;
import com.example.isoftservice.pojos.User;
import com.example.isoftservice.service.UserService;
import com.example.isoftservice.shiro.token.JwtToken;
import com.example.isoftservice.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    private EmailMailUtil mailUtil;
    @Autowired
    UserMapper userMapper;


    @Override
    public Map<String,Object> sendemail(User user) {
        String code = Constants.generateVerifyCode(6);
        System.out.println("数据: " + user);
        Map<String,Object> map=new HashMap<>();
        if (user.getEmail() != null){
            if(userMapper.selectByEmail(user) == null){
                map.put("code",1);
                map.put("msg","用户不存在");
            }else {
                EmailMailBean mailBean = new EmailMailBean();
                mailBean.setRecipient(user.getEmail());//接收者
                mailBean.setSubject("用户信息");//标题
                //内容主体
                mailBean.setContent("云上有个小BUG团队向您发来一条验证码：" + code);

                mailUtil.sendSimpleMail(mailBean);
                map.put("code",0);
                map.put("data",code);
            }

        }else{
            map.put("code",1);
            map.put("msg","请输入邮箱");
        }
        return map;
    }

    @Override
    public Map<String, Object> login(User user) {
        Map<String,Object> map = new HashMap<>();
        User dbuser = userMapper.selectByEmail(user);
        if(dbuser != null) {
            Subject subject = SecurityUtils.getSubject();
            String jwt = JwtUtils.createJWT(dbuser.getUsername(),"isoft","1",1000*60*30);
            JwtToken jwtToken = new JwtToken(jwt);
            subject.logout();
            subject.login(jwtToken);
            map.put("code", 0);
            map.put("msg", "登陆成功!");
            map.put("user", dbuser);
            map.put("jwtToken", jwtToken.getToken());
            return map;
        }else{
            map.put("code",1);
            map.put("msg","登陆失败!");
            return map;
        }

    }
}
